package cn.cloud.butler.uploadapi.service;

import cn.cloud.butler.uploadapi.Utils.DateUtils;
import cn.cloud.butler.uploadapi.domain.OperProduceEntity;
import cn.cloud.butler.uploadapi.logger.WaLogger;
import cn.cloud.butler.uploadapi.repository.OperProduceRepository;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;

@Service
public class OperProduceService {

    @Autowired
    OperProduceRepository operProduceRepository;

    public int saveProduce(String macSn,String name){
        int m = 0;
        OperProduceEntity operProduce = new OperProduceEntity();
        operProduce.setMacsn(macSn);
        operProduce.setProducename(name);
        operProduce.setUploadtime(DateUtils
                .getDateTimeFormat(new Date()));
        operProduce.setDescr(null);
        try {
            m = operProduceRepository.saveAndFlush(operProduce).getId();
        } catch (Exception e) {
            m = -1;
            WaLogger.logger.error("上传单间加工数据失败" + e.toString());
        }
        return m;
    }


    @Transactional
    public int saveMoreProduce(String macsn, JSONArray dataArray, HashMap<String, Long> map) {
        long deltaTime ;
        int m = 0;

        OperProduceEntity operProduce = new OperProduceEntity();
        try {
            for(int i = 0 ; i<dataArray.size();i++){
                JSONObject temp = dataArray.getJSONObject(i);
                String produce = temp.getString("v");
                //对时
                long time = Long.parseLong(temp.getString("t"));
                deltaTime = map.get(macsn);
                long timeSum = time  - deltaTime;
                String timeSumString = Long.toString(timeSum);

                String uploadtime = DateUtils.longToDate(timeSumString);
                operProduce.setMacsn(macsn);
                operProduce.setProducename(produce);
                operProduce.setUploadtime(uploadtime);

                m = operProduceRepository.saveAndFlush(operProduce).getId();
            }
        }catch (Exception e){
            m = -1;
            WaLogger.logger.error("上传机床加工件数列表错误" + e.toString());
        }
        return m;
    }

}
